package com.pubinfo.passbook.common.exception;

import com.pubinfo.passbook.common.model.vo.base.BusinessErrorCode;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.base.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class MyGlobalExceptionHandler {

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("方法参数校验:" + e.getMessage(), e);
        return JsonResult.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * ValidationException
     */
    @ExceptionHandler(ValidationException.class)
    public JsonResult handleValidationException(ValidationException e) {
        log.error("ValidationException:", e);
        return JsonResult.error(e.getCause().getMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public JsonResult handleServiceException(ServiceException e) {
        log.error("ServiceException:", e.getMessage());
        if (Objects.nonNull(e.getData())) {
            if (e.data instanceof BusinessErrorCode) {
                BusinessErrorCode result = (BusinessErrorCode) e.data;
                return JsonResult.error(result.code, result.message);
            } else if (e.data instanceof ResultCode) {
                ResultCode result = (ResultCode) e.data;
                return JsonResult.error(result.code, result.message);
            }
        }
        return JsonResult.error(e.getMessage());
    }


    /**
     * ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult handleConstraintViolationException(ConstraintViolationException e) {
        log.error("ValidationException:" + e.getMessage(), e);
        return JsonResult.error(e.getMessage());
    }

}